<?php
/*
Bitsand - a web-based booking system for LRP events
Copyright (C) 2006, 2007 Russell Peter Phillips

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

//Do not check that user is logged in
$bLoginCheck = False;

include ('inc/inc_head_db.php');
$sMessage = '';

$db_prefix = DB_PREFIX;
if ($_POST ['btnSubmit'] != '') {
	//User is logging in
	$sEmail = SafeEmail ($_POST ['txtEmail']);
	//Get SHA-1 hash of password
	$sPass = sha1 ($_POST ['txtPassword'] . PW_SALT);
	//Set up & run query
	$sql = "SELECT plPlayerID FROM {$db_prefix}players WHERE plEmail LIKE '" . ba_db_real_escape_string ($link, $sEmail) .
		"' AND plPassword = '$sPass'";
	$result = ba_db_query ($link, $sql);
	if (ba_db_num_rows ($result) > 1)
		//Log warning if there was more than one row returned
		LogWarning ("index.php - more than one result from e-mail and password\n$sql");
	//If rows returned, set cookies & redirect to start page
	if (ba_db_num_rows ($result) > 0) {
		//Store player ID & login time in cookies
		$row = ba_db_fetch_assoc ($result);
		$sErr = '';
		//Get values to store in cookies & sessions table
		$iPlayerID = $row ['plPlayerID'];
		//Random string is appended to login time (down to microsecond), then combined string is hashed.
		//Hash is stored in sessions table and in cookie
		$sLoginTime = sha1 (microtime () . RandomString (10, 20));
		$iLastAccess = time ();
		//Set cookies
		if (setcookie ('BA_PlayerID', $iPlayerID) === False)
			$sErr = "<br>\nYou must have cookies enabled to login";
		if (setcookie ('BA_LoginTime', $sLoginTime) === False)
			$sErr = "<br>\nYou must have cookies enabled to login";
		if ($sErr == '') {
			//Cookies set OK. Reset login counter
			$sql = "UPDATE {$db_prefix}players SET plLoginCounter = 0 WHERE plPlayerID = $iPlayerID";
			ba_db_query ($link, $sql);
			//Store details in sessions table then redirect to start page
			$sql = "SELECT ssPlayerID FROM {$db_prefix}sessions WHERE ssPlayerID = $iPlayerID";
			$result = ba_db_query ($link, $sql);
			//Insert new record if no rows returned, otherwise update existing row
			if (ba_db_num_rows ($result) == 0) {
				$sql = "INSERT INTO {$db_prefix}sessions (ssPlayerID, ssLoginTime, ssIP, ssLastAccess) " .
					"VALUES ($iPlayerID, '$sLoginTime', '" .
					ba_db_real_escape_string ($link, $_SERVER ['REMOTE_ADDR']) . "', $iLastAccess)";
			}
			else {
				$sql = "UPDATE {$db_prefix}sessions SET ssLoginTime = '$sLoginTime', ssIP = '" .
					ba_db_real_escape_string ($link, $_SERVER ['REMOTE_ADDR']) . "', ssLastAccess = $iLastAccess " .
					"WHERE ssPlayerID = $iPlayerID";
			}
			//Run query to update/insert session, then redirect to start page
			ba_db_query ($link, $sql);
			//Make up URL & redirect
			$sURL = SYSTEM_URL . 'start.php';
			header ("Location: $sURL");
		}
		else
			//Problem setting cookies. Append error message
			$sMessage .= $sErr;
	}
	else {
		//No rows returned. E-mail or password must be wrong
		if ($sMessage != '')
			$sMessage .= "<br>\n";
		$sMessage .= "Wrong e-mail/password. Please try again";
		//Increment login count and store in players table
		$sql = "SELECT plPassword, plLoginCounter FROM {$db_prefix}players " .
			"WHERE plEmail LIKE '" . ba_db_real_escape_string ($link, $sEmail) . "'";
		$result = ba_db_query ($link, $sql);
		$row = ba_db_fetch_assoc ($result);
		$iLoginCounter = $row ['plLoginCounter'];
		$sql = "UPDATE {$db_prefix}players SET plLoginCounter = " . ++$iLoginCounter . " " .
			"WHERE plEmail LIKE '" . ba_db_real_escape_string ($link, $sEmail) . "'";

		//Check for too many failed logins
		if ($iLoginCounter > LOGIN_TRIES && $row ['plPassword'] != 'ACCOUNT DISABLED') {
			//Change SQL query so that plPassword and plLoginCounter are both updated
			$sql = "UPDATE {$db_prefix}players SET plPassword = 'ACCOUNT DISABLED', plLoginCounter = " . $iLoginCounter .
				" WHERE plEmail LIKE '" . ba_db_real_escape_string ($link, $sEmail) . "'";
			$sMessage = "You have entered an incorrect password too many times. Your account has been disabled.<br>" .
				"An e-mail has been sent to your e-mail address with instructions on how to re-enable your account.";
			//E-mail user
			$sBody = "This is an automated message from " . SYSTEM_NAME . ". Your account has been disabled, because " .
				"an incorrect password was entered too many times. Please contact " . TECH_CONTACT_NAME . " at " .
				TECH_CONTACT_MAIL . " to have your account re-enabled.\n\n" . SYSTEM_URL;
			mail ($sEmail, SYSTEM_NAME . ' - account disabled', $sBody, "From:" . SYSTEM_NAME . " <" . TECH_CONTACT_MAIL . ">");
			//E-mail admin and log a warning
			$sBody = "Account with e-mail address $sEmail has been disabled, after too many failed login attempts. " .
				"An e-mail has been sent to the user.\n\n" . SYSTEM_URL;
			mail (TECH_CONTACT_MAIL, SYSTEM_NAME . ' - account disabled', $sBody, "From:" . SYSTEM_NAME . " <" . TECH_CONTACT_MAIL . ">");
			LogWarning ($sBody);
		}
		elseif ($row ['plPassword'] == 'ACCOUNT DISABLED')
			//Account has been previously disabled. Just display message - do not send e-mail
			$sMessage = "Your account has been disabled. To re-enable it, either <a href = 'retrieve.php'>request a new password</a>" .
				" or e-mail " . TECH_CONTACT_NAME . ", using the link below";
		//Run query to update plLoginCounter (and plPassword, if account is being disabled)
		ba_db_query ($link, $sql) . $sql;
	}
}
else {
	//User is not logging in, so reset login cookies
	//Cookies are reset here, but values will not be available until next page load. Note that Lynx (and others?)
	//do not seem to reset cookies when they are set null value, so we set them to zero, then set them to null
	setcookie ('BA_PlayerID', 0);
	setcookie ('BA_PlayerID', '');
	setcookie ('BA_LoginTime', 0);
	setcookie ('BA_LoginTime', '');
	//Because cookie value will not be available until next page load, reset value of $iPlayerID & $iLoginTime
	$PLAYER_ID = 0;
	$fLoginTime = 0;
}
include ('inc/inc_head_html.php');
?>

<h1><?php echo TITLE?></h1>

<h2>Next Event: <?php echo EVENT_NAME?></h2>

<?php
include ('inc/inc_event.php');
echo ANNOUNCEMENT_MESSAGE;
?>

<p>
<a href = "event.php">Full event details</a>, including pricing details and a printable booking form.
</p>

<p>
To log in, enter your e-mail address and password below, then click <b>Login</b>.
</p>
<?php
//Display message if one was included in URL
if ($_GET ['green'] != '')
	echo "<p class = 'green'>" . htmlentities ($_GET ['green']) . "</p>\n";
if ($_GET ['warn'] != '' || $sMessage != '')
	echo "<p class = 'warn'>" . htmlentities ($_GET ['warn']) . $sMessage . "</p>\n";
?>

<form action = 'index.php' method = 'post'>
<table class = 'blockmid'>
<tr>
<td>E-mail address:</td>
<td><input name = 'txtEmail' class = 'text'></td>
</tr><tr>
<td>Password:</td>
<td><input name = 'txtPassword' type = 'password' class = 'text'></td>
</tr><tr>
<td colspan = '2' class = 'mid'><input type = 'submit' name = 'btnSubmit' value = 'Login'>&nbsp;
<input type = 'reset'></td>
</tr>
</table>
</form>

<ul>
<li>Not registered? <a href = "register.php">Register</a></li>
<li>Forgot your password? <a href = "retrieve.php">Get a new password</a></li>
<li>Please ensure that you have read and understood the <a href = "terms.php">terms &amp; conditions</a></li>
<li><a href = "bookings.php">Booking list</a></li>
<?php
echo "<li>Problem? See the <a href = 'faq.php'>FAQ</a> or <a href = 'mailto:" .
	Obfuscate (EVENT_CONTACT_MAIL) . "'>E-mail " . EVENT_CONTACT_NAME . "</a> with event queries, <a href = 'mailto:" .
	Obfuscate (TECH_CONTACT_MAIL) . "'>E-mail " . TECH_CONTACT_NAME . "</a> with web site problems.</li>\n";
?>
</ul>

<?php
include ('inc/inc_foot.php');
?>
